package com.web.cms.doc.service;

import com.blue.jdbc.JdbcDataSource;
import com.blue.jdbc.Page;
import com.web.cms.doc.dao.ChannelDao;
import com.web.cms.doc.dao.WebDao;
import com.web.cms.doc.model.Channel;
import com.web.core.util.Const;
import io.netty.channel.ChannelException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service("cmsChannelService")
@Transactional
@JdbcDataSource(Const.DS_CMS)
public class ChannelService
{
	@Autowired
	private ChannelDao channelDao;
	@Resource
	private WebDao webDao;
	
	public ChannelService()
	{
	}
	
	public Channel save(Channel channel)
	{
		if (channel.getCode() != null && !channel.getCode().isEmpty() && channelDao.exist(channel, "code", "webId"))
			throw new ChannelException("栏目标识已存在：" + channel.getCode());
		
		if (channel.getParentId() != null)
		{
			Channel c = new Channel();
			c.setId(channel.getParentId());
			if (channelDao.exist(c))
				throw new ChannelException("栏目上级ID【parentId=" + channel.getParentId() + "】不存在");
		}
		
		if (channel.getId() == null)
		{
			channelDao.save(channel);
			webDao.inc(channel.getWebId(), "channels", 1);
		}
		else
		{
			channelDao.update(channel);
		}
		Channel w = channelDao.get(channel.getId());
		return w;
	}
	
	public Channel get(Integer id)
	{
		Channel channel = channelDao.get(id);
		return channel;
	}
	
	public Page<Channel> list(Channel channel, Page<Channel> page)
	{
		page = channelDao.list(channel, page);
		return page;
	}
	
	public List<Channel> list(Channel channel)
	{
		List<Channel> list = channelDao.list(channel);
		return list;
	}
	
}
